class MerchantController < ApplicationController
  include Authorizable
  include MerchantHelper

  def index
    @today_count = Merchant.where("created_at >= ?", beginning_of_today).count
    @week_count = Merchant.where("created_at >= ?", beginning_of_week).count
    @total_count = Merchant.count

    @users = User.select(:id, :name, :mobile, :is_active).
                  where(user_type: USER_TYPE["信息录入员"]).
                  order(:id).
                  page(params[:page]).per(10)
  end

  def show
    if @merchant = Merchant.find_by(id: params[:id])
      render layout: false
    else
      flash[:danger] = "商户不存在"
      redirect_to :back
    end
  end

  def edit
    @merchant = Merchant.find_by(id: params[:id])
  end

  def update
    @merchant = Merchant.find_by(id: params[:id])
    if @merchant.update(gather_merchant_data)
      flash[:danger] = "更新成功"
      redirect_to "/information_clerk/#{@merchant.information_clerk_id}"
    else
      flash[:danger] = "更新失败"
      redirect_to :back
    end
  end

  private
    def gather_merchant_data
      permitted = params.permit(
        :name,
        :phone,
        :business_scope,
        :longitude,
        :latitude,
        :location,
        :is_dtd,
        :service_start,
        :service_end
      )
      permitted[:is_dtd] = params[:is_dtd].nil? ? false : true
      permitted
    end
end